//管理用户数据
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginAPI } from '@/apis/user'
import { useCartStore } from './cartStore'
import {mergeCartAPI} from '@/apis/cart'

export const useUserStore = defineStore('user', () => {
  const cartStore = useCartStore()
  //定义管理用户数据的state
  const userInfo = ref({})
  //定义获取接口数据的action函数
  const getUserInfo = async ({account,password}) => {
  const res = await loginAPI({account,password})
    userInfo.value = res.result
    //登录成功后，将购物车信息合并到服务器
    mergeCartAPI(cartStore.cartList.map(item => {
      return {
        skuId:item.skuId,
        count:item.count,
        selected:item.selected
      }
    }
    ))
    cartStore.upDataNewList()
  }
  //退出时清除用户信息
  const clearUserInfo = () => {
    userInfo.value = {}
    cartStore.clearCart()
  }
  return { userInfo, getUserInfo, clearUserInfo }
},{
  persist:{ enabled:true }
}
)
